package com.jason.rpc;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class Client {
	ICall callclient;

	public ICall getCallclient( String host, int port) {
		return (ICall) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { ICall.class },
				new MyHandler( host, port));
	}

	public Client() {		

	}

	class MyHandler implements InvocationHandler {
		private int port;
		private String host;

		public MyHandler(String host,int port) {
			// TODO Auto-generated constructor stub
			this.host=host;
			this.port = port;
		}

		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			// TODO Auto-generated method stub

			Socket socket =new Socket(host,port);
			ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
			ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
			
			oos.writeObject(ICall.class);
			oos.writeObject(method.getName());
			oos.writeObject(args);
			oos.flush();		
			
			Object res=	ois.readObject();	
			
			return res;
		}

	}

	public static void main(String[] args) {
		Client client = new Client();
		ICall icallclient = client.getCallclient("localhost", 9999);
		String m = icallclient.getMsg();
		int aa = icallclient.getInt();
		icallclient.dosth();
		System.out.println(m);
		System.out.println(aa);

	}

}
